package com.example.mybluetooth;

import android.os.Bundle;
import com.google.android.material.tabs.TabLayout;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.app.AppCompatActivity;

import com.example.mybluetooth.ui.main.SectionsPagerAdapter;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    private ArrayList<Fragment> mFragments;
    private String[] titles = {"扫描", "广播"};
    //viewpager的fragment列表
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        以下注释代码是IDE自动生成带有tab标签的代码
//      setContentView(R.layout.activity_main);
//      SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
//      ViewPager viewPager = findViewById(R.id.view_pager);
//      viewPager.setAdapter(sectionsPagerAdapter);
//      TabLayout tabs = findViewById(R.id.tabs);
//      tabs.setupWithViewPager(viewPager);

        setContentView(R.layout.activity_main_0);
        ViewPager viewPager = findViewById(R.id.mViewPager);
        TabLayout tabs = findViewById(R.id.mTabLayout);

        /*
//        以下是测试通过application对象实现全局数据共享，避免不同对象间传值
        MyApp appState = ((MyApp)getApplicationContext());
        String state = appState.getState();
        System.out.println("这是自定义Application的状态："+state);
        */

//将viewPager和tabs对象传递给以下方法，
        initView(viewPager,tabs);
    }

    /**
     * 初始化组件
     * @param viewPager
     * @param tabs
     */
    private void initView(ViewPager viewPager,TabLayout tabs){
        //初始化Fragment
        mFragments =new ArrayList();
        mFragments.add(new BleScanPageFragment());
        mFragments.add(new BleServerPageFragment());
        //初始化ViewPager的适配器
        FragmentPagerAdapter fragmentPagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public int getCount() {
                return mFragments.size();
            }

            @NonNull
            @Override
            public Fragment getItem(int position) {
                return mFragments.get(position);
            }
        };
//        绑定适配器给viewPager
        viewPager.setAdapter(fragmentPagerAdapter);

        //初始化TabLayout
        for (int i=0;i<titles.length;i++) {
            tabs.addTab(tabs.newTab());
        }
        tabs.setupWithViewPager(viewPager,false);
        for (int i=0; i<titles.length;i++){
            tabs.getTabAt(i).setText(titles[i]);
        }
    }
}